
有三種方法可以安裝 TypeScript
🔗 Online 免安裝版:https://www.typescriptlang.org/play/
有安裝的話可以跳過此步驟。 當你安裝 Node.js 時,npm(Node Package Manager)會自動一起被安裝,可以透過 npm 來安裝 TypeScript
https://www.npmjs.com/package/typescript
npm install -g typescript
--save-dev 代表只在開發階段使用npm install typescript --save-dev
在終端機中,切換到當前資料夾
執行以下指令來初始化 TypeScript Compiler
tsc --init
tsc: TypeScript Compiler
執行後,會生成一個 tsconfig.json 檔案,裡面有先寫好一些默認配置(如下圖),可以在這裡設定 TypeScript 的配置選項
// 默認配置
{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}
以下來依依介紹一下:
(*)或是 require 引入,例如: import * as moment from 'moment'; const moment = require("moment");import 來導入 CommonJS 模組,不需要使用 require。 例如:import moment from 'moment';P.S. import 和 require 差異可以看 seafood 的鐵人文章
.d.ts 文件的型別檢查(此類型的檔案常見於 libraries 或 node_modules)
forceConsistentCasingInFileNames: true
P.S. tsconfig.json 的詳細配置選項後面會再介紹到
.ts: 標準的 Typescript 檔.tsx:React 中的 Typescript 檔
建立好檔案後,執行下方指令就會進行編譯,那為什麼會需要編譯呢?
因為瀏覽器讀不懂 TypeScript,需要編譯成 JavaScript 才能看得懂
tsc 檔案名稱<XXXX.ts>
編譯後會自動生成一個 XXXX.js 的檔案
如果不想要每改動一次就要手動執行一次編譯,可以使用 --watch 參數
這樣檔案在保存的當下就會自動編譯囉~若要取消按 Ctrl + C 即可
tsc --watch
更多的 tsc options 可以點此